package com.redare.dev.smart.generator.sdk.parser;

import com.redare.dev.smart.generator.sdk.pojo.OnlFormField;
import com.redare.dev.smart.generator.sdk.pojo.OnlFormHead;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.create.table.ColDataType;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author yangqy on 2021/8/28
 * @date 2021/8/28 下午10:45
 */
public class DefaultParser extends AbstractParser {



    @Override
    public List<OnlFormHead> parseSql(String sqlString) {
        if (StringUtils.isBlank(sqlString)) {
            return null;
        }
        List<OnlFormHead> result = new ArrayList<>();
        // 解析sql语句
        try {
            List<Statement> statements = CCJSqlParserUtil.parseStatements(sqlString).getStatements();
            if (statements == null || statements.isEmpty()) {
                throw new RuntimeException("Nothing in parse !!!");
            }
            List<CreateTable> createTables = new ArrayList<>();
            for (Statement statement: statements) {
                if (statement instanceof CreateTable) {
                    createTables.add((CreateTable) statement);
                }
            }
            if (createTables.isEmpty()) {
                throw new RuntimeException("仅支持create语句");
            }
            for(CreateTable createTable: createTables) {
                List<OnlFormField> fields = new ArrayList<>();
                OnlFormHead table = new OnlFormHead(fields);
                table.setTableName(removeQuotes(createTable.getTable().getName()));
                table.setSubPath(StringUtils.lowerCase(table.getModel()));
                table.setComment(getTableComment((List<String>) createTable.getTableOptionsStrings()));
                createTable.getColumnDefinitions().forEach(it -> {
                    OnlFormField field = new OnlFormField();
                    // 字段名称
                    String columnName = removeQuotes(it.getColumnName());
                    // 同时设置了 FieldName
                    field.setDbFieldName(columnName);

                    // 字段类型
                    ColDataType colDataType = it.getColDataType();
                    // 同时设置了字段类型
                    field.setDbType(colDataType.getDataType());
                    String length = firstOrNull(colDataType.getArgumentsStringList());
                    field.setDbLength(length==null?-1:Integer.parseInt(length));
                    if (StringUtils.equals(field.getFieldType(),"java.util.Date")){
                        field.setFieldShowType("date");
                    }else{
                        field.setFieldShowType("text");
                    }


                    Set<String> ignoreSet = new HashSet();
                    ignoreSet.add("id");
                    ignoreSet.add("createTime");
                    ignoreSet.add("createUserId");
                    ignoreSet.add("createUserName");
                    ignoreSet.add("updateTime");

                    if (!ignoreSet.contains(field.getField())){
                        field.setShowForm(true);
                        field.setShowList(true);
                    }else{
                        field.setShowForm(false);
                        field.setShowList(false);
                    }

                    //设置字段是否校验非空
                    field.setDbIsNull(!getColumnNotNull(it.getColumnSpecs()));

                    // comment注释
                    String columnComment = getColumnComment(it.getColumnSpecs());

                    field.setShowForm(true);
                    field.setShowInfo(true);

                    field.setComment(columnComment);
                    fields.add(field);
                });

                if (table.getFields() != null && !table.getFields().isEmpty()) {
                    result.add(table);
                }
            }
            return result;
        } catch (Exception ignore) {
            ignore.printStackTrace();
            System.out.println(ignore);
        }
        return null;
    }


    private String getTableComment(List<String> specs) {
        if (specs == null || specs.isEmpty()) {
            return null;
        }
        for (int size = specs.size(), i = 0; i < size; i++) {
            String spec = specs.get(i);
            if ("COMMENT".equals(spec.toUpperCase())) {
                // 下两个为comment内容, 查看是否越界
                if (i + 2 >= size) {
                    return null;
                }
                return removeQuotes(specs.get(i + 2));
            }
        }
        return null;
    }

    private boolean getColumnNotNull(List<String> specs){
        if (specs == null || specs.isEmpty()) {
            return false;
        }
        String s = StringUtils.trim(specs.toString());
        return s.contains("NOT, NULL");
    }

    /**
     * 获取字段的注释
     */
    private String getColumnComment(List<String> specs) {
        if (specs == null || specs.isEmpty()) {
            return null;
        }
        for (int size = specs.size(), i = 0; i < size; i++) {
            String spec = specs.get(i);
            if ("COMMENT".equals(spec.toUpperCase())) {
                // 下一个为comment内容, 查看是否越界
                if (i + 1 >= size) {
                    return null;
                }
                return removeQuotes(specs.get(i + 1));
            }
        }
        return null;
    }
}
